var axios = require('axios');
var fs = require('fs');
var path = require('path');
async function downFile(url, localPath) {
  let { dir, root, base, name, ext } = path.parse(localPath);

  return new Promise((reslove, reject) => {
    mkdir(dir);

    axios({
      url,
      responseType: 'stream',
      retry: 2,
      retryDelay: 0,
      timeout: 1000 * 60 * 3,
      headers: {
        'Accept-Encoding': 'identity;q=1, *;q=0',
        Referer: url,
        'User-Agent':
          'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36' +
          Math.random()

        //   'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1'
      }
    }).then(res => {
      let writer = fs.createWriteStream(localPath);
      writer.on('finish', reslove);
      writer.on('error', reject);
      res.data.pipe(writer);
      res.data.on('end', reslove);
      res.data.on('error', reject);
    }, reject);
  });
}

function mkdir(dir) {
  let dirs = dir.split('/');
  dirs.map((item, index) => {
    let dirPath = dirs.slice(0, index + 1).join('/');
    if (!fs.existsSync(dirPath)) {
      fs.mkdirSync(dirPath);
    }
  });
}
module.exports = downFile;
